const router = require("express").Router();
const express = require("express");
const path = require("path");
const fs = require("fs");
const axios = require("axios");

// 获取banner数据
router.get("/api/banner", (req, res) => {
    // 查询数据库，获取到所有的新闻
    readNewsData("banner.json", (data) => {
        res.jsonp({
            status: 200,
            msg: "查询数据成功",
            data: data.data,
        });
    });
});

// 获取首页列表数据的接口
router.get("/api/indexlist", (req, res) => {
    // let id = req.query.id
    readNewsData("indexlist.json", (data) => {
        res.jsonp({
            status: 200,
            msg: "查询数据成功",
            list: data.data,
        });
    });
});

// 获取定位信息

// 食疗坊 搜索
router.get("/api/foods/search", (req, res) => {
    let name = req.query.name;
    readNewsData("list.json", (data) => {
        let ret = data.filter((item) => {
            if (name && item.name) {
                return item.name.includes(name);
            } else {
                return false;
            }
        });
        res.jsonp({
            status: 200,
            msg: "查询结果成功",
            list: ret,
        });
    });
});

// 根据定位来 分页获取数据  每页10条
router.get("/api/foods/list", (req, res) => {
    let city = req.query.city || "北京";
    let pageIndex = req.query.page;

    readNewsData("list.json", (data) => {
        let rets = data.filter((item) => item.city == city);

        totalPage = Math.ceil(rets.length / 10);

        let goodslists = rets.slice((pageIndex - 1) * 10, pageIndex * 10);

        let msg = "查询数据成功";
        if (!goodslists.length) {
            msg = "没有数据了";
        }

        res.jsonp({
            status: 200,
            msg,
            list: goodslists,
        });
    });
});

// 城市列表数据
router.get("/api/city", (req, res) => {
    readNewsData("city.json", (data) => {
        res.jsonp({
            status: 200,
            msg: "查询城市数据成功",
            list: data,
        });
    });
});

// 根据id 请求对应的indexList 中的数据
router.get("/api/detail", (req, res) => {
    let id = req.query.id;
    readNewsData("list.json", (data) => {
        res.jsonp({
            status: 200,
            msg: "查询数据成功",
            list: data.find((item) => item.id == id),
        });
    });
});

// 根据商品类型 type?type=0
router.get("/api/type", (req, res) => {
    let type = req.query.type;

    readNewsData("list.json", (data) => {
        res.jsonp({
            status: 200,
            msg: "获取类型数据成功",
            list: data.filter((item) => item.type == type),
        });
    });
});

// 添加购物车
router.post("/api/cart/add", (req, res) => {
    console.log(req.body);
    let dataObj = req.body;

    readNewsData("cart.json", (data) => {
        console.log(data);
        let idx = data.findIndex((item) => item.id == dataObj.id);
        if (idx == -1) {
            data.push({
                id: dataObj.id,
                pic: dataObj.pic,
                name: dataObj.name,
                num: dataObj.num,
                selected: dataObj.selected,
                info: dataObj.info,
                price: dataObj.price,
            });
        } else {
            data[idx].num += dataObj.num;
        }

        writeNewsData(data, () => {
            res.send({
                status: 200,
                msg: "添加成功",
            });
        });
    });
});

// 更改商品选择
router.post("/api/cart/selected", (req, res) => {
    let id = req.body.id;
    let selected = req.body.selected;
    readNewsData("cart.json", (data) => {
        let idx = data.findIndex((item) => item.id == id);
        console.log(selected);
        data[idx].selected = selected;
        writeNewsData(data, () => {
            res.send({
                status: 200,
                msg: "操作成功",
            });
        });
    });
});
//  全选更改
router.post("/api/cart/allselected", (req, res) => {
    let selected = req.body.selected;

    readNewsData("cart.json", (data) => {
        data.forEach((item) => {
            item.selected = selected;
        });
        writeNewsData(data, () => {
            res.send({
                status: 200,
                msg: "操作成功",
            });
        });
    });
});

// 获取购物车数据
// 把获取购物车商品数据 接口 改一下 加入权限校验
router.post("/api/cart/list", (req, res) => {
    // console.log(req.headers);
    // console.log("openid号是", req.headers);
    readNewsData('openid.json', data => {
        // 如果前端 传过来的openid 和 session_key 和我后端记录的
        // openid 和 session_key 一致  则校验通过
        // console.log(req.headers.openid, req.headers.session_key);
        if (
            req.headers.openid === data.openid &&
            req.headers.session_key === data.session_key
        ) {
            // 返回数据
            readNewsData("cart.json", (data) => {
                res.jsonp({
                    status: "200",
                    msg: "读取购物车数据成功",
                    list: data,
                });
            });
        } else {
            res.status(400).jsonp({
                msg: "抱歉您没有权限,请您登陆授权",
            });
        }

    })
});
// 删除购物车数据
router.post("/api/cart/delete", (req, res) => {
    let { id } = req.body;
    readNewsData("cart.json", (data) => {
        let idx = data.findIndex((item) => item.id == id);
        data.splice(idx, 1);
        writeNewsData(data, () => {
            res.jsonp({
                status: "200",
                msg: "删除购物车数据成功",
                list: data,
            });
        });
    });
});

// 登陆接口
router.get("/getSession", async(req, res) => {
    let code = req.query.code;
    // 请求微信接口
    // appid： 小程序唯一标识  微信后台---开发设置--appid
    // appsercet： app 密钥  开发设置
    // js_code:获取的登陆凭证码
    try {
        // 下面http地址 微信的授权接口地址
        let data = await axios.get("https://api.weixin.qq.com/sns/jscode2session", {
            params: {
                appid: "wx803267851c53f083",
                secret: "67f4d91b5d823e94b7db49f639abc5b0",
                js_code: code,
            },
        });
        console.log("~~~~~~~~~", data.data); // openid 和 session_key
        // OPEN_ID = data.data.openid;
        // console.log("=======", data.data.openid);
        readNewsData("openid.json", (obj) => {
            obj.openid = data.data.openid;
            obj.session_key = data.data.session_key;

            fs.writeFile(
                path.join(__dirname, "data", "openid.json"),
                JSON.stringify(obj),
                (err) => {
                    if (err) {
                        return console.log("写文件失败", err);
                    }

                    res.jsonp({
                        status: "200",
                        msg: "返回openid和session_key成功",
                        data: obj,
                    });
                }
            );
        });
    } catch (e) {
        res.send(e);
    }
});

module.exports = router;

function readNewsData(filename, callback) {
    fs.readFile(path.join(__dirname, "data", filename), "utf8", (err, data) => {
        if (err) {
            return console.log("读取文件失败", err);
        }
        // console.log(data);
        data = JSON.parse(data);

        callback(data);
    });
}

function writeNewsData(data, callback) {
    // console.log(data);
    fs.writeFile(
        path.join(__dirname, "data", "cart.json"),
        JSON.stringify(data),
        (err) => {
            if (err) {
                return console.log("写文件失败", err);
            }
            callback();
        }
    );
}